package com.bskj.kuaifu.nettyService.service.utils;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.StringUtils;

import io.netty.channel.ChannelHandlerContext;

/**
 * Created by Dell on 2016/2/2.
 */
public class ClientConnectionMap {
	private static final Logger logger = LoggerFactory.getLogger(ClientConnectionMap.class);

	//保存所有的客户端连接
	public static ConcurrentHashMap<String, ClientConnection> allClientMap = new ConcurrentHashMap<>();
	//岗亭和连接映射
	private static ConcurrentHashMap<String, String> box2NetidMap = new ConcurrentHashMap<>();

	public static void addClientConnection(ChannelHandlerContext c) {
		//存放客服端连接
		ClientConnection conn = new ClientConnection(c);
		ClientConnectionMap.allClientMap.putIfAbsent(conn.getNetId(), conn);
	}

	public static void removeClientConnection(ChannelHandlerContext c) {
		//移除客服端连接
		ClientConnection conn = getClientConnection(c);
		String netid = conn.getNetId();
		ClientConnectionMap.allClientMap.remove(netid);

		//移除映射关系
		String boxNo = conn.getBoxNo();
		if (!StringUtils.isBank(boxNo)) {
			ClientConnectionMap.box2NetidMap.remove(boxNo);
		}
	}

	public static ClientConnection getClientConnection(ChannelHandlerContext ctx) {
		String netId = ctx.attr(ClientConnection.NETID).get();
		ClientConnection conn = allClientMap.get(netId);
		if (conn != null) {
			return conn;
		} else {
			logger.error("ClientConenction not found in allClientMap, netId: {}", netId);
		}
		return null;
	}

	public static ClientConnection getClientConnection(String boxNo) {
		String netId = box2NetidMap.get(boxNo);
		if (netId != null) {
			ClientConnection conn = allClientMap.get(netId);
			if (conn != null) {
				return conn;
			} else {
				logger.error("连接数据有误！boxNo ： " + boxNo);
			}
		}
		return null;
	}

	public static void register(ChannelHandlerContext ctx, String boxNo) {
		String netId = ctx.attr(ClientConnection.NETID).get();
		box2NetidMap.put(boxNo, netId);
	}
	
	public static void logAllCollection(){
		LogUtils.info("================全部连接========================");
		LogUtils.info(allClientMap);
		LogUtils.info(box2NetidMap);
		LogUtils.info("=================全部连接end====================");
	}
}
